﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using Autofac.Extras.DynamicProxy;
using CacheAOP_Castle.AOPCache;
using CacheManager;
using CacheManager.IOC;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Reflection;

namespace CacheAOP
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddScoped<ICacheManager, DistributedCacheManager>();
            var redisConnectionString = Configuration.GetSection("ConnectionStrings")["Redis"];
            services.AddDistributedRedisCache(option =>
            {
                option.Configuration = redisConnectionString;//redis连接字符串
                option.InstanceName = "redis1";//Redis实例名称
            });
            services.UseCsRedisClient(redisConnectionString);
            services.AddOptions();

            return this.GetAutofacServiceProvider(services);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseMvc();
        }

        private IServiceProvider GetAutofacServiceProvider(IServiceCollection services)
        {
            var builder = new ContainerBuilder();
            builder.Populate(services);
            var assembly = this.GetType().GetTypeInfo().Assembly;
            builder.RegisterType<CachingInterceptor>();
            //scenario 1
            builder.RegisterAssemblyTypes(assembly)
                         .Where(type => typeof(ICaching).IsAssignableFrom(type) && !type.GetTypeInfo().IsAbstract)
                         .AsImplementedInterfaces()
                         .InstancePerLifetimeScope()
                         .EnableInterfaceInterceptors()
                         .InterceptedBy(typeof(CachingInterceptor));
            //scenario 2
            builder.RegisterAssemblyTypes(assembly)
                         .Where(type => type.Name.EndsWith("BLL", StringComparison.OrdinalIgnoreCase))
                         .EnableClassInterceptors()
                         .InterceptedBy(typeof(CachingInterceptor));
           
            return new AutofacServiceProvider(builder.Build());
        }
    }
}
